package query;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;
import utils.JDBCutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Query_Demo1 {
    @Test
    public void findAll() throws SQLException {
        Connection con = JDBCutils.getConnection();
        String sql = "select  * from  user ";
        PreparedStatement ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        ArrayList<User> list = new ArrayList<>();
        while (rs.next()){
        User user =new User();
        int id = rs.getInt(1);
        String username = rs.getString(2);
        String password = rs.getString(3);
        user.setId(id);
        user.setusername(username);
        user.setPassword(password);
        list.add(user);
        }
        for (User user : list) {
            System.out.println(user.getId() + "\t "+ user.getusername() +"\t"+user.getPassword());
        }
//释放资源
        rs.close();
        ps.close();
        con.close();
    }
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    QueryRunner qr = new QueryRunner(dataSource);
    @Test
    public  void findAllUser() throws SQLException {
    String sql = "select * from user";
        List<User> list = qr.query(sql, new BeanListHandler<User>(User.class));

        for (User user : list) {
            System.out.println(user.getId() + "\t "+ user.getusername() +"\t"+user.getPassword());
        }
    }

    
}
